package com.yunc.modules.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunc.common.utils.BaseConstant;
import com.yunc.modules.shop.entity.Address;
import com.yunc.modules.shop.mapper.AddressMapper;
import com.yunc.modules.shop.service.IAddressService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 地址管理
 *
 * @author congcong tao
 * @create 2018/12/23 10:16 PM
 */
@Service("addressService")
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements IAddressService {

    @Autowired
    private AddressMapper addressMapper;

    @Override
    public Address getDefault(String memberId) {
        // 查询默认的
        QueryWrapper<Address> ew = new QueryWrapper<>();
        ew.eq("member_id", memberId);
        ew.eq("type", "1");
        Address address = this.getOne(ew);
        if (address != null) {
            return address;
        }
        ew = new QueryWrapper<>();
        ew.eq("member_id", memberId);
        ew.orderByAsc("order_num");
        List<Address> list = this.list(ew);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    @Transactional
    public boolean saveAddress(Address address) {
        if (StringUtils.equals(address.getType(), BaseConstant.ADDRESS_TYPE_DEFAULT)) {
            addressMapper.updateDefaultType(null);
        }
        return this.save(address);
    }

    @Override
    @Transactional
    public boolean updateAddress(Address address) {
        if (StringUtils.equals(address.getType(), BaseConstant.ADDRESS_TYPE_DEFAULT)) {
            addressMapper.updateDefaultType(address.getId());
        }
        return this.updateById(address);
    }
}
